package com.basis.message;

import java.lang.reflect.Method;
import java.util.List;
import org.hibernate.Query;
import org.openbravo.base.structure.BaseOBObject;
import org.openbravo.dal.service.OBDal;

public class FilterResultUtil {
	public static boolean check(String where, BaseOBObject baseObj) throws Exception {
		FilterClauseParseUtil util = new FilterClauseParseUtil();
		util.parseWhere(where);
		List<String> paramNames = util.getParamNames();
		
		String sql = "select case when " + where + " then 1 else 0 end from dual";
		for (int i = 0; i < paramNames.size(); i++) {
			sql = sql.replace(paramNames.get(i), ":param_" + i);
		}
		Query query = OBDal.getInstance().getSession().createSQLQuery(sql);
		for (int i = 0; i < paramNames.size(); i++) {
			query.setParameter("param_" + i, getValue(paramNames.get(i), baseObj));
		}
		long size = (Long)query.uniqueResult();
		if (size > 0) {
			return true;
		}
		return false;
	}
	
	private static Object getValue(String param, BaseOBObject baseObj) throws Exception {
		String[] params = param.split("\\.");
		Object obj = baseObj;
		for (int i = 0; i < params.length; i++) {
			if ((i == 0 && "e".equals(params[i])) || "".equals(params[i].trim())) {
				continue;
			}
			obj = getValue(params[i], obj);
			if (obj == null) {
				return null;
			}
		}
		return obj;
	}
	
	private static Object getValue(String field, Object obj) throws Exception {
		Method method = obj.getClass().getMethod(toMethodName(field));
		return method.invoke(obj);
	}
	
	private static String toMethodName(String field) {
		return "get" + field.substring(0, 1).toUpperCase() + field.substring(1);
	}
}
